<?php
class EWebby_HttpHandlerFactory {
	public static function create($application) {
		$request = urldecode( $_SERVER['REQUEST_URI'] );
		$queryString = urldecode( $_SERVER['QUERY_STRING'] );
		
		if( strlen($queryString) > 0 ) {			
			$indx = strrpos($request, '?' . $queryString);
		} else {
			$indx = strrpos($request, '?');
		}
		if( $indx > -1 ) {
			$request = substr($request, 0, $indx);			
		}				
		
		$requestURI = explode('/', $request);
		$scriptName = explode('/',$_SERVER['SCRIPT_NAME']);
		for($i= 0;$i < sizeof($scriptName);$i++) {
      		if ( strtolower(urldecode($requestURI[$i])) == strtolower($scriptName[$i]) ) {
                unset($requestURI[$i]);
            }
      	}
      	
		$urlArray = array_values($requestURI);
		if ( count($urlArray) == 0 ) {
			$urlArray[] = '';
		}
		
		if( count($urlArray) > 0 ) {
			if( count($urlArray) == 1 && trim($urlArray[0]) == '' ) {
				$className = $application->defaultHandler;					
			} else {
				$pageName = implode('/', $urlArray);				
				$fullName = substr($pageName, 0, strrpos($pageName, '.'));
				$className = str_replace('/', '_', $fullName);
			}
			$className = $application->handlersDirectory . '_' . $className;				
			$application->handlerFile = APP_PATH . str_replace('_', DIRECTORY_SEPARATOR, $className);

			try {				
				return new $className();
			} catch (EWebby_Runtime_Exception $ex) {
				$application->handlerFile = APP_PATH . $pageName;
				if( file_exists($application->handlerFile) ) {
					return new EWebby_ContentHandler();
				}
			}
		}
		
		return null;
	}
}